package com.baidu.shoppingmall.auth.service.impl;

import com.baidu.shoppingmall.auth.dao.AuthorityDAO;
import com.baidu.shoppingmall.auth.domain.AuthorityDTO;
import com.baidu.shoppingmall.auth.domain.AuthorityPO;
import com.baidu.shoppingmall.auth.service.AuthorityService;
import com.baidu.shoppingmall.auth.composite.AuthorityNode;
import com.baidu.shoppingmall.auth.visitor.CheckRoleAuthorityRelationVisitor;
import com.baidu.shoppingmall.auth.visitor.DeleteAuthorityVisitor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yjf
 */
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityDAO,AuthorityPO> implements AuthorityService {

    /**
     * 权限管理模块的DAO组件
     */
    @Autowired
    private AuthorityDAO AuthorityDAO;

    @Autowired
    private CheckRoleAuthorityRelationVisitor checkRoleAuthorityRelationVisitor;
    @Autowired
    private DeleteAuthorityVisitor deleteAuthorityVisitor;

    /**
     * 查询根权限
     * @return 根权限集合
     */
    @Override
    public List<AuthorityDTO> listRootAuthorities() {
        //构造器，构造parent_id=null的条件查询条件
        QueryWrapper<AuthorityPO> queryWrapper=new QueryWrapper();
        Map<String, Object> map = new HashMap<>();
        map.put("parent_id", null);
        queryWrapper.allEq(map);
        //查询所有的根权限
        List<AuthorityPO> AuthorityPOs = AuthorityDAO.selectList(queryWrapper);
        //创建一个集合 用于存储DTO的数据
        List<AuthorityDTO> AuthorityDTOs = new ArrayList<>(AuthorityPOs.size());

        //把PO的数据 拷贝到DTO中
        for(AuthorityPO AuthorityDO : AuthorityPOs) {
            AuthorityDTOs.add(AuthorityDO.clone(AuthorityDTO.class));
        }
        return AuthorityDTOs;
    }

    /**
     * 根据id查询权限
     * @param id 权限id
     * @return 权限
     */
    @Override
    public AuthorityDTO getAuthorityById(Long id) {
        //通过id查询权限
        AuthorityPO authorityPO = AuthorityDAO.selectById(id);
        if (authorityPO!=null){
            return authorityPO.clone(AuthorityDTO.class);
        }
        return null;
    }

    /**
     * 新增权限
     * @param authorityDTO 权限authorityDTO对象
     * @return 新增成功的记录条数
     */
    @Override
    public Integer saveAuthority(AuthorityDTO authorityDTO) {
        AuthorityPO authorityPO = authorityDTO.clone(AuthorityPO.class);
        Integer count = AuthorityDAO.insert(authorityPO);
        return count;
    }

    /**
     * 更新权限
     * @param authorityDTO 权限authorityDTO对象
     * @return 更新成功的记录条数
     */
    @Override
    public Integer updateAuthority(AuthorityDTO authorityDTO) {

        AuthorityPO authorityPO = authorityDTO.clone(AuthorityPO.class);
        Integer count=AuthorityDAO.updateById(authorityPO);
        return count;
    }

    /**
     * 根据父权限id查询子权限
     * @param parentId 父权限id
     * @return 子权限
     */
    @Override
    public List<AuthorityDTO> listChildAuthorities(Long parentId) {
        //构造器，构造parent_id=parentId的条件查询条件
        QueryWrapper<AuthorityPO> queryWrapper=new QueryWrapper();
        Map<String, Object> map = new HashMap<>();
        map.put("parent_id", parentId);
        queryWrapper.allEq(map);
        //查询父id下的所有子权限
        List<AuthorityPO> AuthorityPOs = AuthorityDAO.selectList(queryWrapper);
        //创建一个集合 用于存储DTO的数据
        List<AuthorityDTO> AuthorityDTOs = new ArrayList<>(AuthorityPOs.size());

        //把PO的数据 拷贝到DTO中
        for(AuthorityPO AuthorityDO : AuthorityPOs) {
            AuthorityDTOs.add(AuthorityDO.clone(AuthorityDTO.class));
        }
        return AuthorityDTOs;
    }

    /**
     * 根据id删除所有权限
     * @param id
     * @return
     */
    @Override
    public Integer delete(Integer id) {
        //通过id查询权限
        AuthorityPO authorityPO = AuthorityDAO.selectById(id);
        try {
            AuthorityNode authorityNode = authorityPO.clone(AuthorityNode.class);
            checkRoleAuthorityRelationVisitor.visit(authorityNode);
            //Boolean status = checkRoleAuthorityRelationVisitor.getStatus();
            //System.out.println(status);
            //没有被占用进入删除
//            if (!status) {
                //调用递归删除对象中的递归删除方法，
                // 在里面也有可能抛异常（当选中被删除节点没有被占用，然后进入递归删除，而它的子类洋有被占用时就会删除出错，因为数据库有外键关联）
                deleteAuthorityVisitor.visit(authorityNode);
                //没有被占用就抛异常，返回给servlet（delete方法）接收
//            } else {
//                throw new RuntimeException("有权限被占用");
//            }
        } catch (Exception e) {
            //当递归删除出错就回滚，并抛出异常
            e.printStackTrace();
            return 0;
        }
    return 1;
    }
}
